package com.earthea.scaffold.system.controller;

import com.earthea.scaffold.common.aop.annotation.ControllerLog;
import com.earthea.scaffold.common.entity.BaseRsp;
import com.earthea.scaffold.common.entity.PageResult;
import com.earthea.scaffold.common.enums.OperateTypeEnum;
import com.earthea.scaffold.common.util.ExcelUtil;
import com.earthea.scaffold.common.util.SecurityUtils;
import com.earthea.scaffold.domain.OperLog;
import com.earthea.scaffold.domain.User;
import com.earthea.scaffold.system.entity.request.OperLogReq;
import com.earthea.scaffold.system.service.OperLogService;
import com.earthea.scaffold.system.service.UserService;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 操作日志记录
 */
@RestController
@RequestMapping("/api/system/operlog")
public class OperLogController {
    @Autowired
    private OperLogService operLogService;

    @Autowired
    private UserService userService;

    @GetMapping()
    public PageResult<OperLog> list(OperLogReq req) {
        setCreateUser(req);
        return operLogService.selectPage(req.addOrder());
    }

    @ControllerLog(title = "操作日志导出", operateType = OperateTypeEnum.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OperLogReq req) {
        setCreateUser(req);
        PageResult<OperLog> info = operLogService.selectPage(req.addOrder());
        ExcelUtil.export(response, "操作日志", info.getRows(), OperLog.class);
    }

    private void setCreateUser(OperLogReq req) {
        if (SecurityUtils.getLoginUser().isAdmin()) {
            if (StringUtils.isNotBlank(req.getCreateUser())) {
                // admin用户可以按用户搜索
                req.setUserId(Optional.ofNullable(userService.selectByUser(req.getCreateUser())).map(User::getUserId).orElse(null));
            } else {
                // admin用户可以看所有日志
                req.setUserId(null);
            }
        }
    }

    @ControllerLog(title = "操作日志删除", operateType = OperateTypeEnum.DELETE)
    @DeleteMapping("/{operIds}")
    public BaseRsp remove(@PathVariable("operIds") List<Long> operIds) {
        return operLogService.deleteByIds(operIds);
    }

    @ControllerLog(title = "操作日志清空", operateType = OperateTypeEnum.CLEAN)
    @DeleteMapping("/clean")
    public BaseRsp clean() {
        operLogService.clean();
        return BaseRsp.success();
    }
}
